<template>
  <el-main class="userBody">
    <el-steps :active="active" finish-status="success">
      <el-step title="验证邮箱"></el-step>
      <el-step title="修改密码"></el-step>
    </el-steps>
    <el-form
      v-if="active === 0"
      ref="pwdForm"
      :model="pwdForm"
      :rules="rules"
      class="form"
      label-position="right"
      label-width="100px"
    >
      <el-form-item label="邮箱" prop="email">
        <el-col :span="14">
          <el-input v-model="pwdForm.email"></el-input>
        </el-col>
        <el-col :span="10" class="userBody__sendCode">
          <el-button
            type="primary"
            round
            size="small"
            plain
            :disabled="emailCodeStatus"
            @click.stop.prevent="sendEmailCode"
            >{{ emailCodeText }}</el-button
          >
        </el-col>
      </el-form-item>
      <el-form-item label="验证码" prop="verificationCode">
        <el-input v-model="pwdForm.verificationCode"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('pwdForm')"
          >下一步</el-button
        >
        <el-button @click="resetForm('pwdForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form
      v-else-if="active === 1"
      ref="changePwdForm"
      :model="changePwdForm"
      :rules="changePwdRules"
      class="form"
      label-position="right"
      label-width="100px"
    >
      <el-form-item label="密码" prop="pwd">
        <el-input v-model="changePwdForm.pwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="重复密码" prop="rePwd">
        <el-input v-model="changePwdForm.rePwd" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('changePwdForm')"
          >下一步</el-button
        >
        <el-button @click="resetForm('changePwdForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row v-else class="pwdSuccess">
      <i class="el-icon-circle-check"></i>密码修改成功,
      <nuxt-link to="/" type="primary" :underline="false">返回登录</nuxt-link>
    </el-row>
  </el-main>
</template>

<script>
import { checkEmail } from '@/assets/js/check'
import secret from '@/assets/js/utils/secret'
export default {
  name: 'ChangePwd',
  data() {
    const validatepwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.changePwdForm.rePwd !== '') {
          this.$refs.changePwdForm.validateField('rePwd')
        }
        callback()
      }
    }
    const validatepwd2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.changePwdForm.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      emailCodeStatus: false,
      emailCodeFocus: false,
      emailCodeText: '发送校验码',
      active: 0,
      pwdForm: {
        email: '',
        verificationCode: ''
      },
      rules: {
        email: [{ validator: checkEmail, trigger: 'blur' }],
        verificationCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      changePwdForm: {
        pwd: '',
        rePwd: ''
      },
      changePwdRules: {
        pwd: [{ validator: validatepwd, trigger: 'blur' }],
        rePwd: [{ validator: validatepwd2, trigger: 'blur' }]
      }
    }
  },
  methods: {
    changeEmailCodeButton() {
      this.emailCodeStatus = true
      let second = 60
      const time = setInterval(() => {
        this.emailCodeText = `再次发送(${--second})`
        if (second === 0) {
          clearInterval(time)
          this.emailCodeStatus = false
          this.emailCodeText = '发送校验码'
        }
      }, 1000)
    },
    async sendEmailCode() {
      const value = this.pwdForm.email.trim()
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        this.$message({
          message: '邮箱不能为空',
          type: 'warning'
        })
        return
      }
      if (!mailReg.test(value)) {
        this.$message({
          message: '请输入正确的邮箱格式',
          type: 'warning'
        })
        return
      }
      const { status, data } = await this.$axios.get('/public/ECode', {
        params: { email: value }
      })
      if (status === 200) {
        if (data.code === 0) {
          this.$message({
            message: data.msg,
            type: 'success'
          })
          this.changeEmailCodeButton()
        } else if (data.code === -1) {
          this.$message({
            message: data.msg,
            type: 'error'
          })
        }
      }
    },
    next() {
      if (this.active++ > 2) this.active = 0
    },
    submitForm(formName) {
      const self = this
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (formName === 'changePwdForm') {
            const { status, data } = await self.$axios.patch('/user/pwd', {
              email: self.pwdForm.email,
              pwd: secret.Encrypt(self.changePwdForm.pwd),
              rePwd: secret.Encrypt(self.changePwdForm.rePwd)
            })
            if (status === 200) {
              if (data.code === 0) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.next()
              } else {
                this.$message({
                  message: data.msg,
                  type: 'error'
                })
              }
            } else {
              this.$message({
                message: '请检查网络',
                type: 'error'
              })
            }
          }
          if (formName === 'pwdForm') {
            const { status, data } = await self.$axios.get('/user/pwdECode', {
              params: {
                email: self.pwdForm.email,
                ecode: self.pwdForm.verificationCode
              }
            })
            if (status === 200) {
              if (data.code === 0) {
                this.next()
              } else {
                this.$message({
                  message: data.msg,
                  type: 'error'
                })
              }
            }
          }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.userBody {
  margin: 0 auto;
  padding: 40px 60px;
  width: $--typeArea;
  height: 1000px;
  background: #fff;
}
.form,
.pwdSuccess {
  margin: 200px auto;
  width: 400px;
}
.pwdSuccess {
  @include font(30px);
  @include flexCenter();
  & i {
    margin-right: 10px;
    @include font(40px, $color: $--color-primary);
  }
  /deep/ a {
    @include font(30px, $color: $--color-primary);
  }
}
.el-form-item {
  height: 40px;
  /deep/ & > * {
    height: 100%;
  }
}

.userBody__sendCode {
  height: 100%;
  @include flexCenter();
}
</style>
